package com.ctl.szmd.szmd.feature_wm.ui.fragment

import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.ctl.lib_common.base.BaseConstants
import com.ctl.lib_common.extensions.singleClick
import com.ctl.lib_common.utils.LocalCache
import com.ctl.szmd.szmd.feature_wm.Constants
import com.ctl.szmd.szmd.feature_wm.R
import com.ctl.szmd.szmd.feature_wm.databinding.FragmentWmLoginBinding
import com.ctl.szmd.szmd.feature_wm.ui.base.BaseWmBindingFragment
import com.ctl.szmd.szmd.feature_wm.ui.viewmodel.WmLoginViewModel
import com.gyf.immersionbar.ImmersionBar
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.koin.android.viewmodel.ext.android.viewModel


class WmLoginFragment : BaseWmBindingFragment<FragmentWmLoginBinding>() {
    private val viewModel: WmLoginViewModel by viewModel()
    override fun getLayoutId(): Int {
        return R.layout.fragment_wm_login
    }

    override fun initImmersionBar() {
        immersionBar {
            transparentBar()
            fitsSystemWindows(false)
        }
        binding.toolbar.run {
            setPadding(
                paddingLeft,
                paddingTop + ImmersionBar.getStatusBarHeight(requireActivity()),
                paddingRight,
                paddingBottom
            )
        }
    }

    @ExperimentalCoroutinesApi
    override fun initView() {
        binding.vm = viewModel
        lifecycle.addObserver(viewModel)

        binding.imgBack.singleClick {
            findNavController().popBackStack(R.id.wmMainFragment, true)
        }

        binding.edtPhone.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                viewModel.userName.value = s.toString()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        binding.edtPassword.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                viewModel.userPw.value = s.toString()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        binding.llRemember.singleClick {
            viewModel.isRemember.value = !viewModel.isRemember.value!!
        }

        viewModel.isRemember.observe(viewLifecycleOwner, Observer {
            LocalCache.getInstance().put(Constants.LOCAL_CACHE_MW_LOGIN_REMEMBER, it)
            if (!it) {
                LocalCache.getInstance().removeKey(Constants.LOCAL_CACHE_MW_LOGIN_PHONE)
                LocalCache.getInstance().removeKey(Constants.LOCAL_CACHE_MW_LOGIN_PASSWORD)
            }
        })

        binding.btnLogin.singleClick {
            if (viewModel.userName.value.isNullOrBlank()) {
                ToastUtils.showShort("请输入手机号!")
                return@singleClick
            }
            if (viewModel.userPw.value.isNullOrBlank()) {
                ToastUtils.showShort("请输入密码!")
                return@singleClick
            }
            if (viewModel.isRemember.value!!) {
                LocalCache.getInstance()
                    .put(Constants.LOCAL_CACHE_MW_LOGIN_PHONE, viewModel.userName.value)
                LocalCache.getInstance()
                    .put(Constants.LOCAL_CACHE_MW_LOGIN_PASSWORD, viewModel.userPw.value)
            }
            viewModel.getLoginInfo()
                .observe(viewLifecycleOwner, Observer {
                    // 将数据显示在页面上
                    if (!it.msg.isNullOrBlank()) {
                        ToastUtils.showShort(it.msg!!)
                    }
                    if (it.code == 1) {
                        LocalCache.getInstance().put(BaseConstants.LOCAL_CACHE_MW_TOKEN, it.token)
                        LocalCache.getInstance().put(BaseConstants.LOCAL_CACHE_MW_UID, it.userId)
                        findNavController().popBackStack(R.id.wmMainFragment, false)
                    }
                })

        }

    }


    override fun onResume() {
        super.onResume()
        requireView().isFocusableInTouchMode = true
        requireView().requestFocus()
        requireView().setOnKeyListener(View.OnKeyListener { _, i, keyEvent ->
            LogUtils.i(" " + keyEvent.action + "  " + i)
            if (keyEvent.action == KeyEvent.ACTION_UP && i == KeyEvent.KEYCODE_BACK) {
                requireView().findNavController().popBackStack(R.id.wmMainFragment, true)
                return@OnKeyListener true
            }
            false
        })
    }


}